/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2jserver.gameserver.communitybbs.Manager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;

import javolution.util.FastMap;

import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.cache.HtmCache;
import com.l2jserver.gameserver.faction.Faction;
import com.l2jserver.gameserver.faction.FactionManager;
import com.l2jserver.gameserver.model.L2World;
import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
import com.l2jserver.gameserver.templates.StatsSet;

/**
* @author Laikeriz
*/
public class FactionBBSManager extends BaseBBSManager
{
	public static Map<Integer, StatsSet> factionsInfo = new FastMap<Integer, StatsSet>();
	public static StatsSet pvpInfo = new StatsSet();
	public static StatsSet pkInfo = new StatsSet();
	
	private FactionBBSManager()
	{
	}
	
	public static void init()
	{
		ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new LoadTask(), 1, 120000);
	}
	
	@Override
	public void parsecmd(String command, L2PcInstance activeChar)
	{
		if (command.startsWith("_bbsfaction"))
		{
			int factionId = Integer.parseInt(command.split(";")[1]);
			String content = HtmCache.getInstance().getHtm("data/html/faction/community_bbs.htm");
			content = updateWithOnlineCount(content);
			content = updateWithFactionsTop(content, factionId);
			separateAndSend(content, activeChar);
		}
		
		else if (command.startsWith("_bbs"))
		{
			String content = HtmCache.getInstance().getHtm("data/html/faction/community_bbs.htm");
			content = updateWithOnlineCount(content);
			content = updateWithTop(content);
			separateAndSend(content, activeChar);
		}
		
	}
	
	public String updateWithOnlineCount(String htm)
	{
		StringBuilder text = new StringBuilder();
		text.append("<table>");
		for (Faction faction : FactionManager.factions.values())
		{
			text.append("<tr><td><font color=" + faction.stringNameColor + ">" + faction.getName() + " Online: </font></td>");
			text.append("<td>" + faction.playersOnline.size() + "</td></tr>");
		}
		text.append("<tr><td width=150><br>Jogadores Online: </td><td>" + L2World.getInstance().getAllPlayersCount() + "</td></tr>");
		text.append("</table>");
		htm = htm.replace("%onlineCount%", text.toString());
		return htm;
	}
	
	public String updateWithTop(String htm)
	{
		StringBuilder text = new StringBuilder();
		text.append("<tr><td align=center><font color=777777>Top 20 Mortes</font></td><td align=center><font color=777777>Top 20 Sprees</font></td></tr>");
		text.append("<tr><td align=center><img src=\"l2ui.squaregray\" width=220 height=1 align=left>");
		text.append("<br><table width=270 bgcolor=555555 cellpadding=3>");
		if (pvpInfo.getInteger("playersCount") > 0)
		{
			for (int i = 1; i <= pvpInfo.getInteger("playersCount"); i++)
			{
				Faction faction = FactionManager.getFactionById(pvpInfo.getInteger("factionId" + i));
				text.append("<tr>");
				text.append("<td>" + i + ".</td>");
				text.append("<td><font color=" + faction.stringNameColor + ">" + pvpInfo.getString("name" + i) + "</font></td>");
				text.append("<td>" + pvpInfo.getInteger("kills" + i) + " Mortes</td>");
				text.append("</tr>");
			}
		}
		text.append("</table><br>");
		text.append("<img src=\"l2ui.squaregray\" width=220 height=1 align=left></td>");
		text.append("<td align=center><img src=\"l2ui.squaregray\" width=220 height=1 align=left>");
		text.append("<br><table width=270 bgcolor=555555 cellpadding=3>");
		if (pkInfo.getInteger("playersCount") > 0)
		{
			for (int i = 1; i <= pkInfo.getInteger("playersCount"); i++)
			{
				Faction faction = FactionManager.getFactionById(pkInfo.getInteger("factionId" + i));
				text.append("<tr>");
				text.append("<td>" + i + ".</td>");
				text.append("<td><font color=" + faction.stringNameColor + ">" + pkInfo.getString("name" + i) + "</font></td>");
				text.append("<td>" + pkInfo.getInteger("kills" + i) + " Sprees</td>");
				text.append("</tr>");
			}
		}
		text.append("</table><br>");
		text.append("<img src=\"l2ui.squaregray\" width=220 height=1 align=left></td></tr>");
		htm = htm.replace("%tops%", text.toString());
		return htm;
	}
	
	public String updateWithFactionsTop(String htm, int factionId)
	{
		StringBuilder text = new StringBuilder();
		StatsSet tempSet = factionsInfo.get(factionId);
		Faction faction = FactionManager.getFactionById(factionId);
		text.append("<tr><td align=center><font color=LEVEL>Top 20 " + faction.getName() + " Kills</font></td><td align=center><font color=LEVEL>Top 20 " + faction.getName() + " Spree</font></td></tr>");
		text.append("<tr><td align=center><img src=\"L2UI_CH3.onscrmsg_pattern01_1\" width=300 height=32 align=left>");
		text.append("<table width=270 bgcolor=555555><tr><td width=20>Pos.</td><td>Name</td><td>Points</td><td>Faction</td></tr>");
		if (tempSet.getInteger("pvpPlayersCount") > 0)
			for (int i = 1; i <= tempSet.getInteger("pvpPlayersCount"); i++)
			{
				text.append("<tr>");
				text.append("<td>" + i + ".</td>");
				text.append("<td>" + tempSet.getString("pvpName" + i) + "</td>");
				text.append("<td>" + tempSet.getInteger("pvpKills" + i) + "</td>");
				text.append("<td><font color=" + faction.stringNameColor + ">" + faction.getName() + "</font></td>");
				text.append("</tr>");
			}
		text.append("</table>");
		text.append("<img src=\"L2UI_CH3.onscrmsg_pattern01_2\" width=300 height=32 align=left></td>");
		text.append("<td align=center><img src=\"L2UI_CH3.onscrmsg_pattern01_1\" width=300 height=32 align=left>");
		text.append("<table width=270 bgcolor=555555><tr><td width=20>Pos.</td><td>Name</td><td>Points</td><td>Faction</td></tr>");
		if (tempSet.getInteger("pkPlayersCount") > 0)
			for (int i = 1; i <= tempSet.getInteger("pkPlayersCount"); i++)
			{
				text.append("<tr>");
				text.append("<td>" + i + ".</td>");
				text.append("<td>" + tempSet.getString("pkName" + i) + "</td>");
				text.append("<td>" + tempSet.getInteger("pkKills" + i) + "</td>");
				text.append("<td><font color=" + faction.stringNameColor + ">" + faction.getName() + "</font></td>");
				text.append("</tr>");
			}
		text.append("</table>");
		text.append("<img src=\"L2UI_CH3.onscrmsg_pattern01_2\" width=300 height=32 align=left></td></tr>");
		htm = htm.replace("%tops%", text);
		return htm;
	}
	
	public static void savePlayers()
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("UPDATE characters SET pvpkills=?,pkkills=? WHERE charId=?");
			for (L2PcInstance player : L2World.getInstance().getAllPlayers().values())
			{
				statement.setInt(1, player.getPvpKills());
				statement.setInt(2, player.getPkKills());
				statement.setInt(3, player.getObjectId());
				statement.execute();
			}
			statement.close();
		}
		catch (Exception e)
		{
		}
		finally
		{
			try
			{
				con.close();
			}
			catch (Exception e)
			{
			}
		}
	}
	
	public static class LoadTask implements Runnable
	{
		public void run()
		{
			Connection con = null;
			
			try
			{
				savePlayers();
				con = L2DatabaseFactory.getInstance().getConnection();
				pvpInfo = new StatsSet();
				pkInfo = new StatsSet();
				pvpInfo.set("playersCount", 0);
				pkInfo.set("playersCount", 0);
				PreparedStatement statement = con.prepareStatement("SELECT char_name,pvpkills,factionId FROM characters WHERE pvpkills > 0 AND accesslevel < 1 AND factionId > 0 ORDER BY pvpkills DESC LIMIT 20");
				ResultSet rset = statement.executeQuery();
				while (rset.next())
				{
					int currentNum = pvpInfo.getInteger("playersCount") + 1;
					pvpInfo.set("playersCount", currentNum);
					pvpInfo.set("name" + currentNum, rset.getString("char_name"));
					pvpInfo.set("kills" + currentNum, rset.getString("pvpkills"));
					pvpInfo.set("factionId" + currentNum, rset.getString("factionId"));
				}
				statement.close();
				rset.close();
				statement = con.prepareStatement("SELECT char_name,pkkills,factionId FROM characters WHERE pkkills > 0 AND accesslevel < 1 AND factionId > 0 ORDER BY pkkills DESC LIMIT 20");
				rset = statement.executeQuery();
				while (rset.next())
				{
					int currentNum = pkInfo.getInteger("playersCount") + 1;
					pkInfo.set("playersCount", currentNum);
					pkInfo.set("name" + currentNum, rset.getString("char_name"));
					pkInfo.set("kills" + currentNum, rset.getString("pkkills"));
					pkInfo.set("factionId" + currentNum, rset.getString("factionId"));
				}
				statement.close();
				rset.close();
				for (Faction faction : FactionManager.factions.values())
				{
					StatsSet tempSet = new StatsSet();
					tempSet.set("pvpPlayersCount", 0);
					tempSet.set("pkPlayersCount", 0);
					statement = con.prepareStatement("SELECT char_name,pvpkills,factionId FROM characters WHERE factionId=? AND pvpkills > 0 AND accesslevel < 1 AND factionId > 0 ORDER BY pvpkills DESC LIMIT 20");
					statement.setInt(1, faction.getFactionId());
					rset = statement.executeQuery();
					while (rset.next())
					{
						int currentNum = tempSet.getInteger("pvpPlayersCount") + 1;
						tempSet.set("pvpPlayersCount", currentNum);
						tempSet.set("pvpName" + currentNum, rset.getString("char_name"));
						tempSet.set("pvpKills" + currentNum, rset.getString("pvpkills"));
						tempSet.set("pvpFactionId" + currentNum, rset.getString("factionId"));
					}
					statement.close();
					rset.close();
					statement = con.prepareStatement("SELECT char_name,pkkills,factionId FROM characters WHERE factionId=? AND pkkills > 0 AND accesslevel < 1 AND factionId > 0 ORDER BY pkkills DESC LIMIT 20");
					statement.setInt(1, faction.getFactionId());
					rset = statement.executeQuery();
					while (rset.next())
					{
						int currentNum = tempSet.getInteger("pkPlayersCount") + 1;
						tempSet.set("pkPlayersCount", currentNum);
						tempSet.set("pkName" + currentNum, rset.getString("char_name"));
						tempSet.set("pkKills" + currentNum, rset.getString("pkkills"));
						tempSet.set("pkactionId" + currentNum, rset.getString("factionId"));
					}
					statement.close();
					rset.close();
					factionsInfo.put(faction.getFactionId(), tempSet);
				}
				statement.close();
				rset.close();
			}
			catch (Exception e)
			{
			}
			finally
			{
				try
				{
					con.close();
				}
				catch (Exception e)
				{
				}
			}
		}
	}
	
	@Override
	public void parsewrite(String ar1, String ar2, String ar3, String ar4, String ar5, L2PcInstance activeChar)
	{
		// TODO Auto-generated method stub
		
	}
	
	public static FactionBBSManager getInstance()
	{
		return SingletonHolder._instance;
	}
	
	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder
	{
		protected static final FactionBBSManager _instance = new FactionBBSManager();
	}
}
